<template>
    <div class="chart" id="kchart"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { init, dispose } from 'klinecharts';

import { kline_data, chartDOM, klinechart_reset } from '@/service/market.js';

import { throttle, debounce } from '@/utils/debounce.js';

const klineStype = {
    candle: {
        tooltip: {
            showRule: 'follow_cross',
            showType: 'rect',
            labels: ['time', 'open', 'close', 'high', 'low', 'volume'],
        }
    },
};

function initKLintChart() {
    // 初始化一个 k线图
    chartDOM.dom = init('kchart', klineStype);
    chartDOM.is_created = true;
    chartDOM.dom.setStyles(klineStype);
    chartDOM.dom.setBarSpace(5);
    chartDOM.dom.setOffsetRightDistance(40);
    chartDOM.dom.setTimezone('America/New_York');
    chartDOM.dom.createIndicator(
        {
            name: 'MA',
            shortName: 'MA',
            calcParams: [10, 20, 30],
            dragEnabled: true,
            plots: [
                { key: 'ma1', title: 'MA10: ', type: 'line' },
                { key: 'ma2', title: 'MA20: ', type: 'line' },
                { key: 'ma3', title: 'MA30: ', type: 'line' }
            ],
            regeneratePlots: (params) => {
                return params.map((p, i) => {
                    return { key: `ma${i + 1}`, title: `MA${p}: `, type: 'line' }
                })
            },
        },
        false,
        { id: "candle_pane", dragEnabled: true, height: 50 }
    );
    chartDOM.dom.applyNewData(kline_data.value, true);
}

watch(klinechart_reset, () => {
    // 解除监听器
    window.removeEventListener('resize', resize_kline);
    // 销毁 k线图
    dispose('kchart');
    chartDOM.is_created = false;
    // 初始化 k线图
    initKLintChart();
    // 重新绑定窗口大小监听器
    window.addEventListener('resize', resize_kline);
});

// 定义重绘函数
const resize_kline = debounce(() => {
    chartDOM.dom.resize();
}, 150);

onMounted(async () => {
    // 等待 DOM 渲染完成
    await nextTick();
    // 初始化一个 k线图
    initKLintChart();
    // 在窗口尺寸改变时重绘 k线图
    window.addEventListener('resize', resize_kline);
});

onUnmounted(() => {
    // 解除监听器
    window.removeEventListener('resize', resize_kline);
    // 销毁 k线图
    dispose('kchart');
    // 销毁 k线图 DOM
    chartDOM.dom = null;
    chartDOM.is_created = false;
});
</script>

<style scoped lang="less">
.chart {
    width: 100%;
    height: 100%;
}
</style>